<template>
  <view class="project-view-container">
    <!-- 顶部查询栏 -->
    <view class="header-bar">
      <input
        class="search-input"
        v-model="searchProject"
        placeholder="输入项目名查询"
      />
      <button class="search-btn" @click="handleSearch">查询</button>
    </view>

    <!-- 护理项目列表 -->
    <view v-for="(item, index) in projectList" :key="index" class="card">
      <view class="card-header">
        <text class="project-name">{{ item.nursingProject.name }}</text>
        <text class="project-price">￥{{ item.nursingProject.price }}</text>
      </view>
      <view class="card-content">
        <text>服务周期：{{ item.nursingProject.cycle }}</text>
        <text>执行频率：{{ item.nursingProject.frequency }}</text>
        <text>描述：{{ item.nursingProject.description }}</text>
        <text
          >服务时间：{{ item.clientNursingProject.startDate }} 至
          {{ item.clientNursingProject.endDate }}</text
        >
        <text>购买次数：{{ item.clientNursingProject.quantity }} 次</text>
      </view>
      <view class="card-footer">
        <button class="nurse-btn" @click="openDialog(item)">护理</button>
      </view>
    </view>

    <!-- 护理弹窗 -->
    <view v-if="dialogVisible" class="dialog-mask">
      <view class="dialog-box">
        <view class="dialog-title">添加护理记录</view>
        <view class="dialog-body">
          <view class="form-item">
            <text>护理时间：</text>
            <text>{{ nursingTime }}</text>
          </view>
          <view class="form-item">
            <text>护理数量：</text>
            <input
              v-model="quantity"
              type="number"
              class="input"
              placeholder="请输入护理数量"
            />
          </view>
        </view>
        <view class="dialog-footer">
          <button @click="confirmNursing" class="confirm-btn">确定</button>
          <button @click="dialogVisible = false" class="cancel-btn">
            取消
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "nursingProjectView",
  data() {
    return {
      clientName: "",
      searchProject: "",
      projectList: [],
      dialogVisible: false,
      selectedItem: null,
      quantity: "",
      nursingTime: "",
      caretakerId: null,

      // 分页相关变量
      page: 1,
      size: 5,
      hasMore: true,
      loading: false,
    };
  },
  onLoad(options) {
    this.clientName = decodeURIComponent(options.clientName || "");
    this.caretakerId = uni.getStorageSync("userId") || 5;
    this.resetAndLoad(false); // 初始不清空搜索框
  },
  onPullDownRefresh() {
    this.resetAndLoad(true); // 下拉刷新时清空搜索框
  },
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.fetchProjectList();
    }
  },
  methods: {
    // 重置并加载数据，清空搜索框的判断由 clearSearch 参数控制
    resetAndLoad(clearSearch) {
      if (clearSearch) {
        this.searchProject = ""; // 清空搜索框
      }
      this.page = 1;
      this.hasMore = true;
      this.projectList = [];
      this.fetchProjectList();
    },

    // 获取当前时间
    getNowTime() {
      const now = new Date();
      const pad = (n) => (n < 10 ? "0" + n : n);
      return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(
        now.getDate()
      )} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(
        now.getSeconds()
      )}`;
    },

    // 处理搜索按钮点击事件
    handleSearch() {
      // 清空分页数据，重新加载数据
      this.resetAndLoad(false); // 保持搜索框内容
    },

    // 获取项目列表
    fetchProjectList() {
      if (!this.hasMore || this.loading) {
        uni.stopPullDownRefresh();
        return;
      }
      this.loading = true;
      uni.request({
        url: "http://localhost:9000/clientNursingProject/pageClientAndProject",
        method: "GET",
        data: {
          cur: this.page,
          number: this.size,
          clientName: this.clientName,
          projectName: this.searchProject,
        },
        success: (res) => {
          if (res.data.status === 200 && Array.isArray(res.data.data)) {
            const newList = res.data.data || [];
            if (this.page === 1) {
              this.projectList = newList;
            } else {
              this.projectList = this.projectList.concat(newList);
            }

            if (newList.length < this.size) {
              this.hasMore = false;
            } else {
              this.page += 1;
              this.hasMore = true;
            }
          } else {
            uni.showToast({
              title: res.data.msg || "暂无护理项目",
              icon: "none",
            });
            this.hasMore = false;
          }
        },
        fail: () => {
          uni.showToast({ title: "接口请求失败", icon: "none" });
          this.hasMore = false;
        },
        complete: () => {
          this.loading = false;
          uni.stopPullDownRefresh();
        },
      });
    },

    // 打开护理弹窗
    openDialog(item) {
      this.selectedItem = item;
      this.nursingTime = this.getNowTime();
      this.quantity = "";
      this.dialogVisible = true;
    },

    // 确认添加护理记录
    confirmNursing() {
      if (!this.quantity || this.quantity <= 0) {
        uni.showToast({ title: "请输入有效护理数量", icon: "none" });
        return;
      }

      const { client, nursingProject } = this.selectedItem;

      uni.request({
        url: "http://localhost:9000/nursingRecord/addNursingRecord",
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        data: {
          nursingTime: this.nursingTime,
          quantity: this.quantity,
          clientId: client.clientId,
          projectId: nursingProject.projectId,
          caretakerId: this.caretakerId,
        },
        success: (res) => {
          if (res.data.status === 200) {
            uni.showToast({ title: "护理记录添加成功", icon: "success" });
            this.dialogVisible = false;
            this.resetAndLoad(false); // 保持搜索框内容，重新加载数据
          } else {
            uni.showToast({ title: res.data.msg || "添加失败", icon: "none" });
          }
        },
        fail: () => {
          uni.showToast({ title: "请求失败", icon: "none" });
        },
      });
    },
  },
};
</script>

<style scoped>
.project-view-container {
  padding: 20rpx;
  background-color: #fffbe6;
  min-height: 100vh;
}
.header-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}
.search-input {
  flex: 1;
  height: 70rpx;
  padding: 0 20rpx;
  background-color: #fff;
  border-radius: 35rpx;
  margin-right: 20rpx;
  border: 1rpx solid #faad14;
}
.search-btn {
  background-color: #faad14;
  color: #fff;
  padding: 0 30rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 35rpx;
  font-size: 28rpx;
  border: none;
}
.card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}
.project-name {
  font-weight: bold;
  font-size: 32rpx;
  color: #faad14;
}
.project-price {
  color: #1890ff;
  font-size: 28rpx;
}
.card-content text {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 8rpx;
}
.card-footer {
  margin-top: 10rpx;
  text-align: right;
}
.nurse-btn {
  background-color: #fa541c;
  color: #fff;
  padding: 8rpx 24rpx;
  border-radius: 24rpx;
  font-size: 26rpx;
  border: none;
}

/* 护理弹窗样式 */
.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: flex-start; /* 改为顶部对齐 */
  justify-content: center;
  z-index: 999;
  padding-top: 100rpx; /* 向下偏移弹窗 */
}
.dialog-box {
  width: 600rpx;
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
}
.dialog-title {
  font-size: 38rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  text-align: center;
}
.dialog-body {
  margin-bottom: 20rpx;
  padding: 0 20rpx; /* ➤ 添加左右边距 */
}
.form-item {
  margin-bottom: 20rpx;
  font-size: 32rpx;
  line-height: 40rpx;
}
.input {
  height: 40rpx; /* 你可以根据需求调整 */
  line-height: 40rpx; /* 与 height 相等可让 placeholder 垂直居中 */
  padding: 0 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #ccc;
  border-radius: 10rpx;
  box-sizing: border-box;
  color: #333;
}
::placeholder {
  color: #aaa;
  font-size: 28rpx;
  line-height: 40rpx; /* 保证一致 */
}
.dialog-footer {
  display: flex;
  justify-content: space-between;
  gap: 20rpx; /* 新增：按钮之间留间距 */
  padding: 0 20rpx; /* 和 .dialog-body 对齐左右边距 */
  box-sizing: border-box;
}
.confirm-btn,
.cancel-btn {
  flex: 1;
  padding: 8rpx 0;
  font-size: 24rpx;
  border-radius: 10rpx;
  color: #fff;
  background-color: #faad14;
  border: none;
}
.cancel-btn {
  background-color: #909399;
}
</style>
